package com.bdqn.petmalldemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.petmalldemo.bo.ShippingAddBo;
import com.bdqn.petmalldemo.common.KetaiException;
import com.bdqn.petmalldemo.common.ResultCodeEnum;
import com.bdqn.petmalldemo.entity.Shipping;
import com.bdqn.petmalldemo.mapper.ShippingMapper;
import com.bdqn.petmalldemo.service.ShippingService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Lenovo
 * @since 2020-02-10
 */
@Service
public class ShippingServiceImpl extends ServiceImpl<ShippingMapper, Shipping> implements ShippingService {

    @Override
    public List<Shipping> getShippingByUserId(String userId) {
        QueryWrapper<Shipping> shippingQueryWrapper = new QueryWrapper<>();
        shippingQueryWrapper.eq("user_id",userId);
        List<Shipping> shippingList = baseMapper.selectList(shippingQueryWrapper);
        return shippingList;
    }

    @Override
    public void addShipping(ShippingAddBo shippingAddBo) {
        //查询当前用户的收货地址
        List<Shipping> shippingList = this.getShippingByUserId(shippingAddBo.getUserId());
        Shipping shipping = new Shipping();
        BeanUtils.copyProperties(shippingAddBo,shipping);
        if (CollectionUtils.isEmpty(shippingList)) {
            //如果满足当前条件,将该地址设为当前用户的默认地址
            shipping.setHasDefault(true);
        }
        //新增一个收货地址
        baseMapper.insert(shipping);
    }


    @Override
    public void deleteShipping(String shippingId) {
        Shipping shipping = baseMapper.selectById(shippingId);
        //判断收货地址是否为默认地址
        if (shipping.getHasDefault()) {
            throw new KetaiException(ResultCodeEnum.DEFAULT_SHIPPING_NOT_ALLOWED_TO_BE_DELETED);
        }
        baseMapper.deleteById(shipping);
    }
}
